package com.zadetk.helpyou.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.zadetk.helpyou.App;
import com.zadetk.helpyou.R;
import com.zadetk.helpyou.base.AbsActivity;
import com.zadetk.helpyou.bean.LogoutResponseBean;
import com.zadetk.helpyou.bean.UpdateInfo;
import com.zadetk.helpyou.net.BaseObserver;
import com.zadetk.helpyou.net.BaseResponse;
import com.zadetk.helpyou.net.LoadApkAsyncTask;
import com.zadetk.helpyou.net.NetTool;
import com.zadetk.helpyou.other.Const;
import com.zadetk.helpyou.other.DataCleanManager;
import com.zadetk.helpyou.other.UserInfoManger;
import com.zadetk.helpyou.utils.SPUtil;
import com.zadetk.helpyou.utils.ToastUtil;
import com.zadetk.helpyou.utils.VersionUtils;

import java.io.File;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.zadetk.helpyou.other.Const.USER_IS_LOGIN;

/**
 * 5-0设置页面
 */
public class SettingActivity extends AbsActivity implements View.OnClickListener {
    private TextView tvAbout;
    private TextView tvUserguide;
    private TextView achor;
    private Switch sw;
    private TextView tvUpdate;
    private TextView tvClean;
    private TextView tvLogout;
    private LinearLayout llClean;
    private UpdateInfo update_info;
    protected Handler loadApkHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LoadApkAsyncTask.LOAD_APK:
                    if ((Boolean) msg.obj) {
                        VersionUtils.installApk(SettingActivity.this, new File(
                                Const.getSavePath(SettingActivity.this), LoadApkAsyncTask.UPDATE_APK_NAME));
                    } else {
                        showUpdateDialog(update_info, "错误提示", "下载失败，请重新下载？");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public int setView() {
        return R.layout.activity_setting;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        initViews();
        initLogic();
    }

    private void initLogic() {
        tvLogout.setOnClickListener(this);
        tvUpdate.setOnClickListener(this);
        llClean.setOnClickListener(this);
        tvAbout.setOnClickListener(this);
        try {
            String size = DataCleanManager.getTotalCacheSize(this);
            tvClean.setText(size);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initViews() {
        setTopTitle("设置");
        tvAbout = (TextView) findViewById(R.id.tv_about);
        tvUserguide = (TextView) findViewById(R.id.tv_userguide);
        achor = (TextView) findViewById(R.id.achor);
        sw = (Switch) findViewById(R.id.sw);
        tvUpdate = (TextView) findViewById(R.id.tv_update);
        tvClean = (TextView) findViewById(R.id.tv_clean);
        tvLogout = (TextView) findViewById(R.id.tv_logout);
        llClean = findViewById(R.id.ll_clean);

        if(!UserInfoManger.isLogin){
            tvLogout.setText("登录");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_logout:
                logout();
                break;
            case R.id.tv_update:
                updateApk();
                break;
            case R.id.ll_clean:
                DataCleanManager.clearAllCache(this);
                ToastUtil.showToast("已清除！");
                tvClean.setText("0k");
                break;
            case R.id.tv_about:
                startActivity(new Intent(SettingActivity.this,AboutActivity.class));
                break;
        }
    }

    private void logout() {
        if(!UserInfoManger.isLogin){
//            ToastUtil.showToast("你未登录！");
            Intent intent = new Intent(this,LoginActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        else {
            Map<String, Object> param = NetTool.newParams(SettingActivity.this);
            NetTool.getApi().logout(param)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponse<LogoutResponseBean>>() {
                        @Override
                        public void onData(BaseResponse<LogoutResponseBean> value) {
                            if(value.getCode() == 0 && value.getData().getStatus() == 1){
                                SPUtil.saveDate(SettingActivity.this, Const.USER_TOKEN,"");
                                SPUtil.saveDate(SettingActivity.this, Const.USER_NAME,"");
                                SPUtil.saveDate(SettingActivity.this,USER_IS_LOGIN,false);
                                SPUtil.saveDate(SettingActivity.this, Const.USER_UID,-1);
                                UserInfoManger.isLogin = false;
                                App.finishAllActivity();
                                startActivity(new Intent(SettingActivity.this,MainActivity.class));
                                ToastUtil.showToast("退出成功！");
                            }else{
                                ToastUtil.showToast("退出登录失败"+value.getMessage());
                            }
                        }
                    });
        }

    }

    private void updateApk() {

        Map<String, Object> params = NetTool.newParams();
        //params.put("uid", AppPreferenceUtil.getUserId(mActivity));
        NetTool.getApi().checkUpdate(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<UpdateInfo>>() {
                    @Override
                    public void onData(BaseResponse<UpdateInfo> value) {
                        UpdateInfo info;
                        if (value != null && (info = value.getData()) != null) {
                            update_info = info;
                            int localVersionCode = VersionUtils.getAppVersionCode(SettingActivity.this);
                            int remoteVersionCode = info.getNumber();
                            if (remoteVersionCode > localVersionCode) {
                                showUpdateDialog(info, "版本升级", "发现新版本！");
                            } else {
                                ToastUtil.showToast("已经是最新版本！");
                            }
                        }
                    }
                });
    }

    protected void showUpdateDialog(final UpdateInfo updateApkInfo, String titleStr, String msgStr) {
        android.app.AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
        builder.setTitle(titleStr);
        builder.setMessage(msgStr);
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new LoadApkAsyncTask(SettingActivity.this, "下载中...", loadApkHandler)
                        .execute(updateApkInfo.getUrl(),
                                String.valueOf(updateApkInfo.getNumber()));
            }
        });

        if (updateApkInfo.getIsForce() == 2) {
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            });
        }
        Dialog dialog = builder.create();
        dialog.show();
    }
}
